import 'dart:async';
import 'dart:io';
import 'dart:ui' as ui;

import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:developer' as developer;
import 'package:path/path.dart' as path;
import '../values/images.dart';

class ImagePath {
  // 加载头像的方法
  ImageProvider get_avatar_image(String? path) {
    try {
      if (path == null || path.isEmpty) {
        return const AssetImage(AssetsImages.avatar);
      }

      // 如果路径以"assets/"开头，则视为资源图片
      if (path.startsWith('assets/')) {
        return AssetImage(path);
      } else if (path.startsWith('app://')) {
        // 对于相对路径，使用自定义ImageProvider异步加载
        return _RelativePathImage(path);
      } else {
        // 否则视为文件路径
        final file = File(path);
        if (file.existsSync()) {
          return FileImage(file);
        } else {
          return const AssetImage(AssetsImages.avatar);
        }
      }
    } catch (e) {
      developer.log('获取头像图片失败: $e');
      return const AssetImage(AssetsImages.avatar);
    }
  }

  // 新增：加载帖子图片的方法
  ImageProvider get_post_image(String? image_path) {
    try {
      if (image_path == null || image_path.isEmpty) {
        return const AssetImage(AssetsImages.defaultPost);
      }

      // 如果路径以"assets/"开头，则视为资源图片
      if (image_path.startsWith('assets/')) {
        return AssetImage(image_path);
      } else if (image_path.startsWith('app://')) {
        // 对于相对路径，使用自定义ImageProvider异步加载
        return _RelativePathImage(image_path);
      } else if (image_path.startsWith('http://') ||
          image_path.startsWith('https://')) {
        // 网络图片
        return NetworkImage(image_path);
      } else {
        // 否则视为文件路径
        final file = File(image_path);
        if (file.existsSync()) {
          return FileImage(file);
        } else {
          // 兼容旧数据格式的图片路径，添加前缀
          return AssetImage('assets/images/$image_path');
        }
      }
    } catch (e) {
      developer.log('获取帖子图片失败: $e', error: e);
      return const AssetImage(AssetsImages.defaultPost);
    }
  }

  // 处理帖子图片列表的方法
  static Future<List<String>> process_post_image_list(
    String image_list_str,
  ) async {
    if (image_list_str.isEmpty) {
      return [];
    }

    List<String> images_list = image_list_str.split(',');
    List<String> processed_images = [];

    for (String img in images_list) {
      // 如果已经是完整路径，直接添加
      if (img.startsWith('assets/') ||
          img.startsWith('app://') ||
          img.startsWith('http://') ||
          img.startsWith('https://') ||
          img.startsWith('/')) {
        processed_images.add(img);
      } else {
        // 如果是短文件名，转换为完整的资源路径
        processed_images.add('assets/images/$img');
      }
    }

    return processed_images;
  }

  // 新增：将绝对路径转换为相对路径
  static Future<String> to_relative_path(String absolute_path) async {
    try {
      // 如果已经是相对路径格式，直接返回
      if (absolute_path.startsWith('app://')) {
        return absolute_path;
      }

      // 如果是资源路径，直接返回
      if (absolute_path.startsWith('assets/')) {
        return absolute_path;
      }

      final app_dir = await getApplicationDocumentsDirectory();
      final base_path = app_dir.path;

      // 检查路径是否以应用文档目录开头
      if (absolute_path.startsWith(base_path)) {
        // 返回相对路径，以特殊前缀开头，表示这是一个相对路径
        final relative_path =
            'app://${absolute_path.substring(base_path.length + 1)}';
        return relative_path;
      }

      // 如果不是应用文档目录中的文件，返回原路径
      return absolute_path;
    } catch (e) {
      return absolute_path;
    }
  }

  // 新增：将相对路径转换为绝对路径
  static Future<String?> _get_absolute_path(String relative_path) async {
    try {
      // 如果不是相对路径格式，直接返回原路径
      if (!relative_path.startsWith('app://')) {
        return relative_path;
      }

      // 检查是否是带有特殊前缀的相对路径
      final app_dir = await getApplicationDocumentsDirectory();
      final path_without_prefix = relative_path.substring(6); // 去除'app://'前缀
      final absolute_path = path.join(app_dir.path, path_without_prefix);

      return absolute_path;
    } catch (e) {
      developer.log('获取绝对路径时出错: $e', error: true);
      return null;
    }
  }

  // 公共方法：获取绝对路径（供其他类使用）
  static Future<String?> get_absolute_path(String path) {
    return _get_absolute_path(path);
  }
}

/// 自定义ImageProvider，处理相对路径图片
class _RelativePathImage extends ImageProvider<_RelativePathImage> {
  final String relative_path;
  final double scale;

  const _RelativePathImage(this.relative_path, {this.scale = 1.0});

  @override
  Future<_RelativePathImage> obtainKey(ImageConfiguration configuration) {
    return SynchronousFuture<_RelativePathImage>(this);
  }

  @override
  ImageStreamCompleter loadImage(
    _RelativePathImage key,
    ImageDecoderCallback decode,
  ) {
    final StreamController<ImageChunkEvent> chunk_events =
        StreamController<ImageChunkEvent>();

    return MultiFrameImageStreamCompleter(
      codec: _loadAsync(key, chunk_events, decode),
      chunkEvents: chunk_events.stream,
      scale: scale,
    );
  }

  Future<ui.Codec> _loadAsync(
    _RelativePathImage key,
    StreamController<ImageChunkEvent> chunk_events,
    ImageDecoderCallback decode,
  ) async {
    try {
      // 转换为绝对路径
      final String? absolute_path = await ImagePath.get_absolute_path(
        relative_path,
      );

      if (absolute_path == null) {
        throw Exception('无法获取绝对路径: $relative_path');
      }

      // 加载文件
      final File file = File(absolute_path);
      if (await file.exists()) {
        final Uint8List bytes = await file.readAsBytes();

        if (bytes.lengthInBytes == 0) {
          throw Exception('文件大小为0: $absolute_path');
        }

        return decode(await ui.ImmutableBuffer.fromUint8List(bytes));
      } else {
        throw Exception('文件不存在: $absolute_path');
      }
    } catch (e) {
      // 加载默认头像
      try {
        final ByteData data = await rootBundle.load(AssetsImages.avatar);
        final Uint8List bytes = data.buffer.asUint8List();
        return decode(await ui.ImmutableBuffer.fromUint8List(bytes));
      } catch (default_error) {
        // 创建一个空的图像作为后备
        final Uint8List empty_bytes = Uint8List(0);
        return decode(await ui.ImmutableBuffer.fromUint8List(empty_bytes));
      }
    } finally {
      chunk_events.close();
    }
  }

  @override
  bool operator ==(Object other) {
    if (other.runtimeType != runtimeType) return false;
    return other is _RelativePathImage &&
        other.relative_path == relative_path &&
        other.scale == scale;
  }

  @override
  int get hashCode => Object.hash(relative_path, scale);

  @override
  String toString() =>
      '${describeIdentity(this)}'
      '($relative_path, scale: $scale)';
}
